package com.sanjiahantang.youjiarole.module.common.presenters;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiarole.base.BaseBean;
import com.sanjiahantang.youjiarole.base.BaseMvpPresenter;
import com.sanjiahantang.youjiarole.base.BaseView;
import com.sanjiahantang.youjiarole.base.CallBack;
import com.sanjiahantang.youjiarole.config.ConfigValue;
import com.sanjiahantang.youjiarole.config.SPConfig;
import com.sanjiahantang.youjiarole.module.common.beans.StringBean;
import com.sanjiahantang.youjiarole.module.common.models.IMainModel;
import com.sanjiahantang.youjiarole.module.common.models.impl.MainModel;
import com.sanjiahantang.youjiarole.utils.SPUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zy on 2017/10/23.
 */

public class BindRolePresenter extends BaseMvpPresenter<BaseView> {
    private IMainModel mainModel;
    public BindRolePresenter(){
        mainModel = new MainModel();
    }

    public void bindRole(final Context context, final String roleCode) {
        Map<String,String> param = new HashMap<>();
        param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        param.put(KEY_PHONE, SPUtils.get(context, SPConfig.PHONE,"").toString());
        param.put("code",roleCode);

        String role = SPUtils.get(context,SPConfig.ROLE_ID,"").toString();
        if (role.length() == 0){
            Utils.showToast(context,"获取角色信息失败!");
            return;
        }
        param.put("role",role.substring(0,1));

        mView.showProgress();
        mainModel.bindRole(context,param, new CallBack<StringBean>() {
            @Override
            public void onSuccess(StringBean response, Context context, Object tag) {
                if (mView == null) return;
                hideProgress();
                Intent intent = new Intent();
                intent.putExtra(BaseView.TAG_DESIGNER_BIND,response);
                ((Activity)context).setResult(Activity.RESULT_OK,intent);
                ((Activity)context).finish();
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                hideProgress();
                Intent intent = new Intent();
                StringBean bean = new StringBean();
                bean.setMessage("服务器错误");
                bean.setCode(1);
                intent.putExtra(BaseView.TAG_DESIGNER_BIND,bean);
                ((Activity)context).setResult(Activity.RESULT_OK,intent);
                ((Activity)context).finish();
            }
        });
    }

    private void hideProgress(){
        if (mView != null){
            mView.hideProgress();
        }
    }
}
